﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.ComponentModel;
using System.Windows.Forms;

namespace DataDownloader
{
    public class CoreDump
    {
        public Form1 form;
        public CoreDump()
        {
            form = new Form1();
        }
        public void DownloadTestMatch(string url, LoginCredentials login, string downloadFolder)
        {
            for (int i = 1; i <= 4; i++)
            {
                for (int j = 1; j < 6; j++)
                {
                    var url_mod = url + "?innings=" + i + ";page=" + j + ";view=commentary";
                    var download_path = downloadFolder + "innings=" + i + "_page=" + j + ".html";
                    if (DownloadFile(url_mod, login, download_path) == -1)
                    {
                        break;
                    }
                    
                }
            }
        }        

        public void DownloadTestSeries(string url, int numTests, LoginCredentials login, string downloadFolder)
        {
            for(int i = 1; i<=numTests; i++)
            {
                int seriesNum = Convert.ToInt32(url.Substring(@"/match/".Length + url.LastIndexOf(@"/match/", StringComparison.OrdinalIgnoreCase)));
                var url_mod = url.Substring(0, @"/match/".Length +url.LastIndexOf(@"/match/", StringComparison.OrdinalIgnoreCase));
                url_mod = url_mod+ seriesNum + ".html";
                var downloadPath = downloadFolder + "_test"+ i + "_";
                DownloadTestMatch(url_mod, login, downloadPath);
            }
        }

        public int DownloadFile(string url, LoginCredentials login, string downloadPath)
        {
            try
            {
                WebClient client = new WebClient();
                client.Proxy = login.proxy;
                //client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
                //client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);

                // Starts the download
                client.DownloadFileAsync(new Uri(url), downloadPath);

                form.button1.Text = "Download In Process";
                form.button1.Enabled = false;
                return 0;
            }
            catch (WebException webException)
            {
                webException.GetType();
                return -1;
            }

        }

        private void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            double bytesIn = double.Parse(e.BytesReceived.ToString());
            double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
            double percentage = bytesIn / totalBytes * 100;
            if (percentage < 0)
            {
                return;
            }
            form.progressBar.Value = int.Parse(Math.Truncate(percentage).ToString());
        }

        private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            MessageBox.Show(" downloaded");
            ////    form.progressBar.Value = 0;
            ////    form.button1.Text = "Start Download";
            ////    form.button1.Enabled = true;
            ////
        }

        public void Download_Series(LoginCredentials login, string inputFile, string downloadFolder)
        {
            var lines = File.ReadAllLines(inputFile);
            foreach (var line in lines)
            {
                if(string.IsNullOrEmpty(line.Trim()))
                {
                    continue;
                }
                var words = line.Split(' ');
                var year = words[0];
                var team1 = words[1];
                var team2 = words[2];
                var numTests = words[3];
                if(!Directory.Exists(Path.Combine(downloadFolder, year)))
                {
                    Directory.CreateDirectory(Path.Combine(downloadFolder, year));
                }
                var downloadSeriesFolder = Path.Combine(downloadFolder, year, team1 + "_" + team2);  
                var url = words[4];
                var innings_list = words[5];
                var matches = innings_list.Split(';');
                for (int i = 1; i <= matches.Length; i++ )
                {
                    DownloadTestMatch(url, login, downloadSeriesFolder+ "_test" + i, matches[i-1]);
                }
            }
        }

        public void DownloadTestMatch(string url, LoginCredentials login, string downloadFolder, string innings_list)
        {
            var innings_details = innings_list.Split('_');
            for (int i = 1; i <=innings_details.Length; i++)
            {
                for (int j = 1; j < 6; j++)
                {
                    var url_mod = url + "?innings=" + i + ";page=" + j + ";view=commentary";
                    var download_path = downloadFolder + "_" + innings_details[i-1]+ "_page=" + j + ".html";
                    if (DownloadFile(url_mod, login, download_path) == -1)
                    {
                        break;
                    }

                }
            }
        }
    }
}
